layui.config({
	base : "js/"
}).use(['form','layer','jquery','laypage','table'],function(){
	var form = layui.form,
		layer = parent.layer === undefined ? layui.layer : parent.layer,
		laypage = layui.laypage,
        table = layui.table,
		$ = layui.jquery;

    $.get("/admin/queryCategoryByType/2",function (msg) {
        if(msg.code == 0){
            var str = "";
            var data = msg.data;
            for(var i=0; i<data.length; i++){
                str += '<option value="'+data[i]['categoryId']+'">'+data[i]['name']+'</option>';
            }
            $("#categoryId").append(str);
        }else{
            layer.alert("加载信息分类出错");
        }
        form.render();
    });
	searchData();

	//批量删除
	$(".batchDel").click(function(){
		layer.msg("delete ...");
	})

	//全选
	form.on('checkbox(allChoose)', function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		child.each(function(index, item){
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断文章是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
		data.elem.checked;
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
		}
		form.render('checkbox');
	})
 
	//操作
	$("body").on("click",".links_edit",function(){  //编辑
		var _this = this;
        var index = layui.layer.open({
            title : "编辑",
            type : 2,
            content : "/message/editMessage/" + $(_this).data("id"),
            end : function(){
                searchData();
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);
	})

	$("body").on("click",".links_del",function(){  //删除
		var _this = $(this);
		layer.confirm('确定删除文章？',{icon:3, title:'提示信息'},function(index){

			$.get("/admin/deleteMessage/"+$(_this).data("id"),function(resp){
				if(resp.code == '0'){
                    _this.parents("tr").remove();
                    layer.msg("删除成功");
				}
			});
			// layer.close(index);
		});
	})

	//分页查询数据，渲染分页Bar
	function searchData(){
        //加载页面数据
        $.ajax({
            url : "/admin/getAllMessage.json",
            type : "get",
			data : {categoryId: $("#categoryId").val()},
            dataType : "json",
            success : function(resp){
                //执行加载数据的方法
                renderDate(resp.result);
                laypage.render({
                    elem : 'pageBar' //注意，这里的 test1 是 ID，不用加 # 号
                    ,count : resp.totalNum //数据总数，从服务端得到
                    ,layout : ['prev', 'page', 'next','limit']
                    ,jump: function(curr, first){
                        layer.msg('数据加载中',{
                            icon : 16,
                            time : 500
                        },function(){
                            if(!first){
                                console.log(curr);
                                $.ajax({
                                    url : "/admin/getAllMessage.json",
                                    data : {
                                        pageNum : curr.curr,
                                        pageSize : curr.limit,
                                        pid : $("#categoryId").val()
                                    },
                                    type : "get",
                                    dataType : "json",
                                    success : function(respp){
                                        console.log("再次填充数据");
                                        renderDate(respp.result);
                                    }
                                })
                            }
                        });

                    }}
                );
            }
        })
	}

	//渲染数据
	function renderDate(data){
		var currData = data;
		var dataHtml = '';
        $(".content").html('');
		if(currData.length != 0){
			for(var i=0;i<currData.length;i++){
				dataHtml += '<tr>'
				+'<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
				+'<td align="left">'+(i+1)+'</td>'
                +'<td>'+(currData[i].imgUrl==null?'暂无图片':'<a  target="_blank" href="'+currData[i].imgUrl+'"><img src="'+currData[i].imgUrl+'"></a>')+'</td>'
                +'<td>'+currData[i].categoryName+'</td>'
				+'<td>'+currData[i].sort+'</td>'
				+'<td>'+currData[i].name+'</td>'
				+'<td>'
				+ '<div><label class="layui-form-label">图文推荐</label><input type="checkbox" messageId="'+currData[i].messageId+'" lay-skin="switch" lay-filter="recommand" lay-text="ON|OFF" '+ (currData[i].isRecommend=='0'?'checked':'')+'></div>'
				+'</td>'
				+'<td>'+currData[i].updateTime+'</td>'
				+'<td>'
				+  '<a class="layui-btn layui-btn-mini links_edit"  data-id="'+data[i].messageId+'"><i class="layui-icon">&#xe642;</i> 编辑</a>'
				+  '<a class="layui-btn layui-btn-danger layui-btn-mini links_del" data-id="'+data[i].messageId+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
				+'</td>'
				+'</tr>';
			}
		}else{
			dataHtml = '<tr><td colspan="17">暂无数据</td></tr>';
		}
		$(".content").html(dataHtml);
		form.render();
	}
	form.on('select(filterCategory)',function(){
		searchData();
	})

    form.on('switch(recommand)',function(data){
        var messageId = $(data.elem).attr("messageId");
        debugger;
        if(data.elem.checked){
            //不推荐
            $.post({
                url : "/admin/addMessage",
                data : JSON.stringify({"messageId":messageId,"isRecommend":"0"}),
                contentType : "application/json;charset=utf-8", //必须，告诉服务器这是json
                success : function(resp){
                    //layer.close(index);
                    if(resp.code == '0'){
                        layer.msg("推荐成功",{icon :1});
                    }else{
                        layer.msg(resp.msg);
                    }
                }
            });
        } else {
            //改为不推荐
            $.post({
                url : "/admin/addMessage",
                data : JSON.stringify({"messageId":messageId,"isRecommend":"1"}),
                contentType : "application/json;charset=utf-8", //必须，告诉服务器这是json
                success : function(resp){
                    //layer.close(index);
                    if(resp.code == '0'){
                        layer.msg("取消推荐成功",{icon :1});
                    }else{
                        layer.msg(resp.msg);
                    }
                }
            });
        }
    })

    $(".addMessage").click(function(){
        var index = layui.layer.open({
            title : "添加新闻",
            type : 2,
            content: '/admin/page/newsInfo/newsAdd.html',
            end : function(){
                searchData();
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);
    })
})
